package com.jy.adscm.wechat.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jy.adscm.support.SimpleCoreResponse;
import com.jy.adscm.utils.AdscmBaseUtils;
import com.jy.adscm.wechat.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.LogRecord;

/**
 * @author zyl
 * @Date 2019/9/23 -11:51
 */

@WebFilter(filterName = "wechatFilter", urlPatterns = "/adscm/wechat/*")
public class WeChatFilter implements Filter {
    @Autowired
    private RedisOperator redis;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse)response;
        resp.setHeader("Access-Control-Allow-Origin","*");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        ObjectMapper mapper = new ObjectMapper();
        SimpleCoreResponse result = new SimpleCoreResponse("401", "please login again", null);
        String resultStr = mapper.writeValueAsString(result);
        if (request instanceof HttpServletRequest){
          HttpServletRequest req = (HttpServletRequest)request;
          String sessionKey = req.getParameter("sessionKey");
          if (!AdscmBaseUtils.getInstance().isNotEmpty(sessionKey,null)){
              PrintWriter writer = resp.getWriter();
              writer.print(resultStr );
              writer.flush();
              writer.close();
          }else {
              String openid = redis.get(sessionKey);
              if(!AdscmBaseUtils.getInstance().isNotEmpty(openid,null)){
                  PrintWriter writer = resp.getWriter();
                  writer.print(resultStr );
                  writer.flush();
                  writer.close();
              }else {
                  chain.doFilter(req,resp);
              }
          }

      }


    }

    @Override
    public void destroy() {

    }
}
